package com.easy.back.utils.error;

import com.easy.back.pojo.ErrorLog;
import com.easy.back.pojo.R;
import com.easy.back.service.IErrorLogService;
import com.easy.back.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;

/**
 * 全局异常
 *
 * @author RuoYu
 * @date 2023/01/05
 */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalException {

    @Autowired
    private IErrorLogService errorLogService;

    /**
     * 运行业务异常
     *
     * @param e e
     * @return {@link R}<{@link String}>
     */
    @ExceptionHandler(CustomException.class)
    public R<String> businessException(CustomException e) {

        String requestURI = ServletUtils.getRequest().getRequestURI();

        ErrorLog errorLog = new ErrorLog();
        errorLog.setLogTime(LocalDateTime.now());
        errorLog.setErrorType("业务异常");
        errorLog.setErrorMessage(e.getMessage());
        errorLog.setErrorUri(requestURI);

        errorLogService.save(errorLog);
        log.error(e.getMessage());
        return R.error(e.getMessage());
    }

    /**
     * 服务器异常
     *
     * @param e e
     * @return {@link R}<{@link String}>
     */
    @ExceptionHandler(Exception.class)
    public R<String> serverException(Exception e) {

        String requestURI = ServletUtils.getRequest().getRequestURI();

        ErrorLog errorLog = new ErrorLog();
        errorLog.setLogTime(LocalDateTime.now());
        errorLog.setErrorType("服务器内部异常");
        errorLog.setErrorMessage(e.getMessage());
        errorLog.setErrorUri(requestURI);

        errorLogService.save(errorLog);
        return R.error("服务器内部异常");
    }

}
